/*
 * This computer program is the confidential information and proprietary trade
 * secret of Apptonelabs, Inc. Possessions and use of this program must
 * conform strictly to the license agreement between the user and
 * Apptonelabs, Inc., and receipt or possession does not convey any rights
 * to divulge, reproduce, or allow others to use this program without specific
 * written authorization of Apptonelabs, Inc.
 * 
 * Copyright (c) 2012-2015 Apptonelabs, Inc. All Rights Reserved.
 */
package com.apptonelabs.vnc.vphone;

import javax.swing.SwingUtilities;

/**
 * This class requests a user name for SSH authentication using JDialog which
 * must be created and operated in the event dispatch thread.
 * 
 * @author const
 */
public class SshUserNameRequester {

	/**
	 * Query SSH user name.
	 * 
	 * @return user name or null if the dialog was canceled by the user.
	 * @throws Exception
	 *             if there was an error.
	 */
	public String queryUserName() throws Exception {
		if (SwingUtilities.isEventDispatchThread()) {
			new DialogRunner().run();
		} else { // not in the event dispatch thread
			SwingUtilities.invokeAndWait(new DialogRunner());
		}
		if (user == null) {
			throw new Exception("No user name entered for SSH authentication");
		}
		return user;
	}

	/**
	 * Private inner class to implement a Runnable object to be executed in the
	 * event dispatch thread.
	 */
	private class DialogRunner implements Runnable {
		public void run() {
			user = null;
			if (!SwingUtilities.isEventDispatchThread()) {
				return; // prevent wrong usage
			}
			SshUserNameDialog dialog = new SshUserNameDialog(null, true);
			dialog.setVisible(true);
			int result = dialog.getReturnStatus();
			if (result == SshUserNameDialog.RET_OK) {
				user = dialog.getUserName();
			}
		}
	}

	private String user;
}
